package com.google.code.ptrends.services.implementations.dataservice;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.google.code.ptrends.entities.ItemValueCollection;
import com.google.code.ptrends.entities.ItemValueRecord;

class ValuesServiceImpl extends DataServiceBaseImpl {

	private static final Logger LOG = Logger.getLogger(ValuesServiceImpl.class);

	protected ValuesServiceImpl(Connection connection) {
		super(connection);
	}

	public ItemValueCollection getValues(final int itemID) throws SQLException {
		ItemValueCollection collection = new ItemValueCollection();
		ItemValueRecord record = null;
		final String queryGetValues = "SELECT parameter_id, value "
				+ "FROM item_values " + "WHERE item_id = ?";
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		SQLException error = null;
		try {
			statement = connection.prepareStatement(queryGetValues);
			statement.setInt(1, itemID);
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				record = new ItemValueRecord();
				record.setParametrID(resultSet.getInt(1));
				record.setValue(resultSet.getString(2));
				if (collection.size() == 0) {
					collection.add(record);
				} else {
					boolean isNew = true;
					for (ItemValueRecord iRecord : collection) {
						if (iRecord.getValue().equals(record.getValue()))
							isNew = false;
					}
					if (isNew) {
						collection.add(record);
					}
				}
			}
		} catch (SQLException e) {
			LOG.error("Error get values", e);
			error = e;
		} finally {
			close(resultSet, statement);
		}
		if (error != null) {
			throw error;
		}
		return collection;
	}

	public boolean saveValue(final int itemID, final ItemValueRecord value)
			throws SQLException {

		if (value == null) {
			throw new IllegalArgumentException(
					"Illegal null-reference saveValue ItemValueRecord");
		} else if (itemID < 0) {
			throw new IllegalArgumentException("Illegal null saveValue itemID");
		}

		boolean result = false;
		final String sqlText = "INSERT INTO item_values (item_id, parameter_id, value) "
				+ "VALUES (?, ?, ?)";

		PreparedStatement preparedStatement = null;
		SQLException error = null;

		try {
			preparedStatement = connection.prepareStatement(sqlText);
			preparedStatement.setInt(1, itemID);
			preparedStatement.setInt(2, value.getParametrID());
			preparedStatement.setString(3, value.getValue());
			preparedStatement.executeUpdate();
			result = true;
		} catch (SQLException e) {
			LOG.error("Problem with Value inserting", e);
			error = e;
		} finally {
			closeStatement(preparedStatement);
		}

		if (error != null) {
			throw error;
		}

		return result;
	}

	public boolean saveValueCollection(final ItemValueCollection ivc)
			throws SQLException {
		if (ivc == null) {
			throw new IllegalArgumentException(
					"Illegal null-reference ItemValueCollection");
		} else if (ivc.isEmpty()) {
			throw new IllegalArgumentException("Empty ItemValueCollection");
		}
		boolean result = false;
		PreparedStatement ps = null;
		SQLException sqlex = null;
		String query = "insert into item_values (value, item_id, parameter_id) values (?, ?, ?)";

		try {
			ps = connection.prepareStatement(query);

			for (ItemValueRecord ivr : ivc) {
				try {
					ps.setString(1, ivr.getValue());
					ps.setInt(2, ivc.getItemID());
					ps.setInt(3, ivr.getParametrID());
					ps.executeUpdate();
				} catch (SQLException e) {
					LOG.warn("Error inserting new item value", e);
					continue;
				}
			}
			result = true;
		} catch (SQLException e) {
			LOG.error("Error executing saving value collection", e);
			sqlex = e;
		} finally {
			closeStatement(ps);
		}
		if (sqlex != null)
			throw sqlex;
		return result;
	}
}
